<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>实例事件</title>
  <script src="../assets/js/vue.min.js"></script>
</head>
<body>
  <h1>实例事件</h1>
  <hr>
  <div id="app">
    {{ num }}
    <br>
    <button @click='add'>add</button>
  <!-- <button @click='reduceOnce'>reduceOnce</button> -->
  </div>
  <button onclick='reduce()'>reduce</button>
  <br>
  <button onclick='reduceOnce()'>reduceOnce</button>
  <br>
  <button onclick='off()'>off</button>
  <script>
    var vue = new Vue({
      el: '#app',
      data: {
        num: 1
      },
      methods: {
        add: function () {  
          this.num ++;
        },
        // reduce: function () { 
        //   this.num --;
        // }
        // reduceOnce: function() {
          // 这样写也可以
        //   vue.$emit('reduceOnce');
        // }
      }
    })
    vue.$on('reduce', function () { 
      // 连续多次
      this.num --;
    })
    function reduce() { 
      vue.$emit('reduce');
    }
    vue.$once('reduceOnce', function (a) {
      console.log(a); 
      // 只执行一次
      this.num --;
    })
    function reduceOnce() {
      vue.$emit('reduceOnce', 2);
    }
    function off() {
      // 关闭事件
      vue.$off('reduce');
      vue.$off('reduceOnce');
    }
  </script>
</body>
</html>